using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;
namespace WinChat02
{
    public class nw_client
    {
        private Form1 RefMainForm;
        public nw_client(Form1 Window) { RefMainForm = Window; }
        public Socket client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public void Start_Client()
        {
            RefMainForm.label1.Text = "Status Client";
            try
            {
                string IP_ADDRESS = "192.168.1.77";
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(IP_ADDRESS), 11000);
                client_socket.Connect(ipEndPoint);
                RefMainForm.Log.Text += "\n Connected: " + IP_ADDRESS +"\n";
                RefMainForm.SetVisibility(true);
            }
            catch (Exception)
            {
                RefMainForm.Log.Text += "\n Error: can't to connected \n";
            }
        }
        public void SendMsg(string data)
        {
            byte[] bytes = new byte[1024];
            bytes = Encoding.UTF8.GetBytes(data);
            client_socket.Send(bytes);
        }
        public int Recive_Data(out string data)
        {
            if (client_socket.Connected)
            {
                byte[] bytes = new byte[1024];
                int bytesRec = client_socket.Receive(bytes);
                data = new string(Encoding.UTF8.GetString(bytes, 0, bytesRec).ToCharArray());
               //  RefMainForm.Chat.Text += string.Format("Received: {0}\n", data);
             }
            else data = null;
            return 0;
        }
        public void ReceiveThread()
        {
            client_socket.Blocking = false;
            string data = null;
            byte[] bytes = new byte[1024];
            if (client_socket.Connected)
                if (client_socket.Poll(0, SelectMode.SelectRead))
                {
                    int bytesRec = client_socket.Receive(bytes);
                    if (bytesRec > 0)
                    {
                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        RefMainForm.Chat.Text += string.Format("He: {0} {1}", data, Environment.NewLine);
                        if (data == "!exit")
                        {
                            client_socket.Close();
                        };
                    }
                }
            //do{
            //    Recive_Data(out data);
            //    if (data == "!exit") 
            //    {
            //        client_socket.Close();
            //    }
            //    Thread.Sleep(1);
            //} while (client_socket.Connected);
        }
    }
}
